<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}管理后台{% endblock %} - 心理咨询系统</title>
    <link href="{{ url_for('static', filename='css/bootstrap.min.css') }}?v=1.0" rel="stylesheet">
    <link href="{{ url_for('static', filename='css/bootstrap-icons.css') }}?v=1.0" rel="stylesheet">
    <link href="{{ url_for('static', filename='css/admin.css') }}?v=4.0" rel="stylesheet">
    {% block extra_css %}{% endblock %}
</head>
<body>
    <!-- 移动端警告 -->
    <div class="mobile-warning d-md-none">
        <div class="text-center">
            <i class="bi bi-exclamation-triangle-fill text-warning me-2"></i>
            <strong>提示：</strong>管理后台建议在电脑端使用以获得最佳体验
            <button class="btn btn-sm btn-primary ms-3" onclick="toggleSidebar()">
                <i class="bi bi-list"></i> 菜单
            </button>
        </div>
    </div>

    <div class="d-flex">
        <!-- 侧边栏 -->
        {% include 'admin/sidebar.html' %}

        <!-- 主内容区 -->
        <main class="main-content flex-fill">
            <!-- 顶部导航栏 -->
            <div class="top-bar">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h3 class="mb-0">{% block page_title %}管理后台{% endblock %}</h3>
                        <small class="text-muted">{% block page_subtitle %}{% endblock %}</small>
                    </div>
                    <div class="d-flex align-items-center">
                        {% block top_actions %}{% endblock %}
                        <span class="badge bg-success me-3">在线</span>
                        <div class="dropdown">
                            <a class="btn btn-outline-secondary dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
                                <i class="bi bi-person-circle me-1"></i>{{ current_admin.username if current_admin else '管理员' }}
                            </a>
                            <ul class="dropdown-menu">
                                <li><a class="dropdown-item" href="#"><i class="bi bi-person me-2"></i>个人资料</a></li>
                                <li><a class="dropdown-item" href="#"><i class="bi bi-gear me-2"></i>设置</a></li>
                                <li><hr class="dropdown-divider"></li>
                                <li><a class="dropdown-item" href="#" onclick="adminLogout()"><i class="bi bi-box-arrow-right me-2"></i>退出登录</a></li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 页面内容 -->
            <div class="content-area">
                {% block content %}{% endblock %}
            </div>
        </main>
    </div>

    <!-- JavaScript -->
    <script src="{{ url_for('static', filename='js/bootstrap.bundle.min.js') }}"></script>
    
    <!-- 通用API请求工具 -->
    <script>
        // 通用的API请求函数
        function apiRequest(url, options = {}) {
            const adminToken = localStorage.getItem('adminToken');
            if (!adminToken) {
                alert('请先登录');
                window.location.href = '/admin/login';
                return Promise.reject(new Error('No token'));
            }

            // 设置默认headers
            const defaultHeaders = {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + adminToken
            };

            // 合并headers
            options.headers = { ...defaultHeaders, ...(options.headers || {}) };

            return fetch(url, options)
                .then(response => {
                    if (response.status === 401) {
                        // token过期或无效
                        localStorage.removeItem('adminToken');
                        alert('登录已过期，请重新登录');
                        window.location.href = '/admin/login';
                        throw new Error('Unauthorized');
                    }
                    
                    // 检查响应是否成功
                    if (!response.ok) {
                        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                    }
                    
                    return response.json();
                })
                .catch(error => {
                    if (error.message !== 'Unauthorized') {
                        console.error('API请求失败:', error);
                        // 如果是网络错误或其他错误，提供更友好的错误信息
                        if (error.name === 'TypeError' && error.message.includes('fetch')) {
                            throw new Error('网络连接失败，请检查网络连接');
                        }
                    }
                    throw error;
                });
        }

        // 显示操作结果的通用函数
        function showResult(success, message, callback = null) {
            if (success) {
                alert(message || '操作成功');
                if (callback) callback();
            } else {
                // 处理undefined或空消息的情况
                const errorMsg = message || '操作失败，请稍后重试';
                alert('操作失败: ' + errorMsg);
                console.error('操作失败详情:', message);
            }
        }
        
        // 管理员退出登录
        function adminLogout() {
            if (confirm('确定要退出登录吗？')) {
                apiRequest('/api/admin/logout', {
                    method: 'POST'
                })
                .then(response => {
                    if (response.success) {
                        localStorage.removeItem('adminToken');
                        localStorage.removeItem('adminInfo');
                        alert('退出登录成功');
                        window.location.href = '/admin-portal';
                    } else {
                        alert('退出登录失败: ' + response.message);
                    }
                })
                .catch(error => {
                    console.error('退出登录失败:', error);
                    // 即使请求失败，也清除本地存储并跳转到登录页
                    localStorage.removeItem('adminToken');
                    localStorage.removeItem('adminInfo');
                    window.location.href = '/admin-portal';
                });
            }
        }
    </script>
    
    {% block extra_js %}{% endblock %}

    <script>
        // 移动端侧边栏切换
        function toggleSidebar() {
            const sidebar = document.getElementById('sidebar');
            sidebar.classList.toggle('show');
        }

        // 点击主内容区域时隐藏侧边栏（移动端）
        document.querySelector('.main-content').addEventListener('click', function() {
            if (window.innerWidth < 768) {
                const sidebar = document.getElementById('sidebar');
                sidebar.classList.remove('show');
            }
        });
    </script>
</body>
</html>